package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.CrmMapLocationAdapter;
import com.jianyun.jyzs.constant.SysConstant;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jianyun.jyzs.utils.RceLog;
import com.jianyun.jyzs.utils.UtilsStyle;

/**
 * Created by yangshijun on 2018/6/4.
 */

public class CrmMapLocationActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.map)
    MapView mMapView;
    @BindView(R.id.searchText)
    TextView searchText;
    @BindView(R.id.searchLyout)
    RelativeLayout searchLyout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private static final int LOCATION_SEARCH = 100;
    private double latitude;
    private double longitude;
    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    int currentPage = 1;
    private CrmMapLocationAdapter adapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.crm_map_layout);
        ButterKnife.bind(this);
        initData( savedInstanceState);
    }

    private void initData(Bundle savedInstanceState) {
        topBack.setVisibility(View.VISIBLE);
        topText.setVisibility(View.VISIBLE);
        topText.setText("选择地址");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CrmMapLocationAdapter(this);
        recyclerView.setAdapter(adapter);
        PoiSearch.Query query = new PoiSearch.Query("", "120000", "");
        final PoiSearch poiSearch = new PoiSearch(this, query);
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        mMapView.onCreate(savedInstanceState);

        //初始化地图控制器对象
        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
                @Override
                public void onCameraChange(CameraPosition cameraPosition) {

                    latitude = cameraPosition.target.latitude;
                    longitude = cameraPosition.target.longitude;
                    poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude,
                            longitude), 1000));
                    poiSearch.searchPOIAsyn();

                }

                @Override
                public void onCameraChangeFinish(CameraPosition cameraPosition) {

                }
            });
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResult poiResult, int i) {
                    RceLog.d("lml", "onPoiSearched");
                    ArrayList<PoiItem> pois = poiResult.getPois();
                    adapter.setList(pois);
                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {
                    RceLog.d("lml", "onPoiItemSearched");
                }
            });
            setUpMap();
        }
    }



    private void setUpMap() {
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.ic_location));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick({R.id.topBack, R.id.searchLyout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.searchLyout:
                ActivityOptionsCompat transitionActivityOptions =
                        ActivityOptionsCompat.makeSceneTransitionAnimation(this, searchText, "crmsearch");
                ActivityCompat.startActivityForResult(this, new Intent(this, SearchCrmLocationActivity.class), LOCATION_SEARCH, transitionActivityOptions.toBundle());
                break;
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点

            } else {
                String errText = "定位失败_______," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("lml", errText);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == LOCATION_SEARCH & data != null) {
                setResult(RESULT_OK, data);
                finish();
            }
        }
    }

    public void getLocationResult(PoiItem poiItem) {
        Intent intent = new Intent();
        intent.putExtra(SysConstant.msg_key_parcelable, poiItem);
        setResult(RESULT_OK, intent);
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mlocationClient.onDestroy();
    }
}
